import 'dart:async';
import 'package:flame/components.dart';
import 'package:flame/effects.dart';
import 'package:flame/flame.dart';
import 'package:freedom/page/mahjong/common/common_card.dart';
import 'package:freedom/page/mahjong/mahjong_game.dart';
import '../bloc/user_state.dart';
import '../common/card_build.dart';
import '../common/mahjong_context.dart';
import 'abstract_card_area.dart';
import '../util/user_location.dart';

class RightCardArea extends AbstractHand with HasGameRef<MahjongIndexGame> {
  var userCardImage = Flame.images.fromCache('mahjong/user/right/usercard.png');
  RightCardArea()
      : super(
            anchor: Anchor.topCenter,
            size: MahjongContext().lrCardAreaSize,
            position: MahjongContext().rightHandCardAreaPoint);
  @override
  FutureOr<void> onLoad() {
    //debugMode = true;
  }

  @override
  Direction userDirection() {
    return Direction.RIGHT;
  }

  @override
  Future<void> reflashUI(UserState userState, {List<int>? highlight}) async {
    currentUserState = userState;
    Set<Component> tempSet = Set.from(children);
    for (var item in tempSet) {
      remove(item);
    }

    int? touchCard = currentUserState.touchCard;
    // 不要添加手牌,手牌单独处理
    List<int> userHandCards =
        currentUserState.getUserHandCards(addTouch: false);
    // 判断用户的手牌数量
    int length = userHandCards.isNotEmpty
        ? userHandCards.length
        : currentUserState.handCardCount;
    // 是否添加手牌 三种情况
    if (!currentUserState.win) {
      if (currentUserState.touchCard != null) {
        addTouchCard(currentUserState.touchCard);
      } else if (userHandCards.isNotEmpty && userHandCards.length % 3 == 2) {
        touchCard = userHandCards[length];
        length = length - 1;
        addTouchCard(touchCard);
      } else if (length % 3 == 2) {
        addTouchCard(null);
      }
    } else {
      addWinCard(currentUserState.winCard!);
    }
    //与手牌产生落差感
    double fistY = userHandCards.isEmpty
        ? MahjongContext().lrCardSize.y *
            (1 - MahjongContext().leftHandCardSegRatio) *
            1.5
        : MahjongContext().lrCardSize.y * 2;
    // 按照手牌总数生成手牌
    for (int i = length, j = 0; j < i; j++) {
      PositionComponent cardComponent;
      if (userHandCards.isNotEmpty) {
        cardComponent = CardBuildUtil.rightExport(
            Vector2(0, fistY), userHandCards[j],
            handCard: true)
          ..angle = radians(270);
      } else {
        cardComponent = SpriteComponent(
            sprite: Sprite(userCardImage),
            size: MahjongContext().lrCardSize,
            position: Vector2(0, fistY));
      }
      add(cardComponent);
      fistY +=
          MahjongContext().lrCardSize.y * MahjongContext().leftHandCardSegRatio;
    }
    // 第一个碰杠牌的位置 根据手牌的高度位移
    //fistY = MahjongContext().lrTBCardSize.x;
    fistY = size.y;
    var pointX = -MahjongContext().lrTBCardSize.y * 1.5;
    currentUserState.openDeal?.forEach((pItem) {
      // 获取是处理的谁的牌
      Direction? pointTo;
      if (pItem.targetUserSeq != null) {
        pointTo = LocationUtil.buildLocationUtil(MahjongContext.userCount,
            currentUserState.seq, pItem.targetUserSeq!,
            location: Direction.RIGHT);
      }
      var index = 0;
      var cardIndex = 100;
      pItem.cardList?.forEach((crt) {
        index++;
        cardIndex--;
        var showPointTo =
            (index == 4 && pItem.cardList!.length == 4) || index == 2;
        PositionComponent cardInfo;
        if (index == 4 && pItem.cardList!.length == 4) {
          // 产生两个横向位移 减去 斜面高度
          fistY += MahjongContext().lrTBCardSize.x *
              (2 - MahjongContext().lrHandCardImageHBRatio);
          cardInfo = CardBuildUtil.rightExport(Vector2(pointX, fistY), crt,
              pointTo: showPointTo ? pointTo : null,
              size: MahjongContext().lrTBCardSize)
            ..priority = cardIndex + 3
            ..angle = radians(270);
        } else if (pItem.type == 2) {
          cardInfo = CardBuildUtil.rDarkExport(Vector2(pointX, fistY),
              size: MahjongContext().lrTBCardSize)
            ..priority = cardIndex
            ..angle = radians(270);
        } else {
          cardInfo = CardBuildUtil.rightExport(Vector2(pointX, fistY), crt,
              pointTo: showPointTo ? pointTo : null,
              size: MahjongContext().lrTBCardSize)
            ..priority = cardIndex
            ..angle = radians(270);
        }
        add(cardInfo);
        if (index == 4 && pItem.cardList!.length == 4) {
          fistY -= MahjongContext().lrTBCardSize.x;
        }
        // 每一次新增正面的距离 斜面不算
        fistY -= MahjongContext().lrTBCardSize.x *
            MahjongContext().lrHandCardImageHBRatio;
      });
      fistY -= MahjongContext().lrTBCardSize.x / 2;
    });
  }

  @override
  Vector2 getHandFirstCardPoint() {
    return Vector2(0, 0);
  }

  /// 新增出牌
  @override
  Component? addTouchCard(int? card) {
    if (TOUCH_CARD != null) {
      TOUCH_CARD!.removeFromParent();
    }
    TOUCH_CARD = card == null
        ? (SpriteComponent(
            sprite: Sprite(userCardImage),
            size: MahjongContext().lrCardSize,
            position: Vector2(0, 0))
          ..priority = -1)
        : (CardBuildUtil.rightExport(
            Vector2(0, MahjongContext().lrCardSize.y), card,
            handCard: true)
          ..angle = radians(270)
          ..priority = -1);
    add(TOUCH_CARD!);
    return TOUCH_CARD;
  }

  @override
  void addWinCard(int card) {
    add(CardBuildUtil.rightExport(
        Vector2(-(MahjongContext().lrTBCardSize.y - size.x) / 2,
            MahjongContext().lrTBCardSize.x),
        card,
        pointTo: null,
        size: MahjongContext().lrTBCardSize)
      ..angle = radians(-90));
  }

  @override
  void exportCard(int? card, {ExportCallBack? callBack}) {
    var rightExport = gameRef.rightExportArea!;
    Vector2 touchCardPoint;
    // 如果能看到手牌 那就直接明牌
    if (currentUserState.getUserHandCards().isNotEmpty && children.isNotEmpty) {
      TOUCH_CARD = children.lastWhere((element) =>
          element is CommonCard &&
          element.handCard &&
          element.cardCode == card) as CommonCard;
    } else {
      // 这里原则上要开放,开发阶段屏蔽调 为了方便动画展示
      TOUCH_CARD ??= addTouchCard(card);
    }
    touchCardPoint = (TOUCH_CARD as PositionComponent).position;

    Vector2 pointByScc = rightExport.getLastPointByScc(touchCardPoint);
    // 特殊处理因为   明牌和暗牌 高度不一样 这里会造成抖动
    if (currentUserState.getUserHandCards().isEmpty) {
      pointByScc.y -= MahjongContext().lrExportCardSize.y;
    }
    Effect effect = MoveByEffect(
      pointByScc,
      EffectController(duration: 0.3),
    );
    TOUCH_CARD!.add(effect);
    effect.onComplete = () {
      TOUCH_CARD?.removeFromParent();
      TOUCH_CARD = null;
      rightExport.defaultExportCard(card!);
      reflashUI(currentUserState);
      if (callBack != null) {
        callBack(rightExport.eportAllCard);
      }
    };
  }

  @override
  void removeCard(int exportCard) {
    if (TOUCH_CARD != null) {
      TOUCH_CARD!.removeFromParent();
    }
  }
}
